package com.zhongbo.java.websocket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhongbo.java.websocket.mapper.ChatHistoryMapper;
import com.zhongbo.java.websocket.model.ChatHistory;
import com.zhongbo.java.websocket.service.IChatHistoryService;
import com.zhongbo.java.websocket.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 说明：
 *
 * @author 钟波dellNotebook
 * @since 2025年03月20日 星期四 14:30:00
 */
@Service
public class ChatHistoryServiceImpl implements IChatHistoryService {

    @Autowired
    private ChatHistoryMapper chatHistoryMapper;

    @Override
    public ChatHistory add(ChatHistory chatHistory) {
        if(chatHistory==null){
            throw new RuntimeException("消息内容不能为空");
        }
        // 记录消息时间
        chatHistory.setTime(new Date());
        int insert = chatHistoryMapper.insert(chatHistory);
        if(insert>0){
            return chatHistory;
        }
        throw new RuntimeException("插入消息历史失败");
    }

    // 分页查询消息历史记录
    @Override
    public PageVo<ChatHistory> listChatHistory(Integer pageNumber, Integer pageSize) {
        QueryWrapper<ChatHistory> queryWrapper  = new QueryWrapper<>();
        // 返回结果按照时间倒序排序
        queryWrapper.orderByDesc("time");
        IPage<ChatHistory> pageParam = new Page<>(pageNumber,pageSize);
        IPage<ChatHistory> chatHistoryIPage = chatHistoryMapper.selectPage(pageParam, queryWrapper);
        return new PageVo<>(chatHistoryIPage);
    }

}
